<?php
/**
 * Created by IntelliJ IDEA.
 * User: admin
 * Date: 4/22 0022
 * Time: 19:56
 */

namespace app\index\model;

use app\api\model\Bdwaimai;
use app\api\model\Meituan;
use think\Session;

/**
 * 处理各种平台订单
 * Class Orders
 * @package app\index\model
 */
class Orders
{

    /**
     * 查询订单分流
     * @param $condition
     * @return array
     */
    public static function searchorder($condition){
        $res=[];
        //TODO
        switch ($condition["platform"]){
            //饿了么
            case "1":
                $elemodel=new Eleorder();
                $res=$elemodel->getorder($condition);
                break;
            //美团外卖
            case "2":
                $jdmodel=new Jdorder();
                $res=$jdmodel->getOrders($condition);
                break;
            //百度外卖
            case "3":
                $res=self::getBaidu($condition);
                break;
            //美团点评团购券
            case "4":
                $res=self::getMeituanTG($condition);
                break;
            //美团点评闪付
            case "5":
                $res=self::getMeituanSH($condition);
                break;
            //百度糯米
            case "6":
                //TODO
                break;
            default:
                break;
        }
        return $res;
    }


    /**
     * 获得美团团购订单
     * @param $conditio
     * @return array
     */
    public static function getMeituanTG($condition){
        $meituan=new Meituan();
        $res=$meituan->where("shopid",Session::get("shopid"))->find();
        if(!isset($res["epoiid"])){
            return false;
        }
        if(empty($res["tuantoken"])){
            return false;
        }
        $appAuthToken=$res["tuantoken"];


        $ePoiId=$res['epoiid'];
        $token=$res['token'];
        $time=time();
        $url="http://api.open.cater.meituan.com/waimai/poi/queryPoiInfo?timestamp=$time&appAuthToken=$token&charset=UTF-8&ePoiIds=$ePoiId";
        $signKey=$meituan->SignKey($url);
        $url=$url."&sign=".$signKey;
        $json=curl_get($url);
        $shopinfo=json_decode($json,true);

        $history=[];
        $endtime=date_create($condition["endtime"]);
        $starttime=date_create($condition["starttime"]);
        $diff=date_diff($endtime,$starttime);
        for($i=0;$i<=$diff->days;$i++){
            $date=date("Y-m-d",strtotime("-".$i." day",$endtime->getTimestamp()));
            $offset=0;
            do{
                $time = time();
                $url = "http://api.open.cater.meituan.com/tuangou/coupon/queryListByDate?appAuthToken=$appAuthToken&charset=UTF-8&timestamp=$time&date=$date&offset=$offset&limit=50";
                $signKey = $meituan->SignKey($url);
                $url = $url."&sign=".$signKey;
                $json =curl_get($url);
                $res=json_decode($json,true);
//            dump($res);
                $offset+=50;
                if(isset($res["data"]["couponCodes"]))$history=array_merge($history,$res["data"]["couponCodes"]);
            }while(isset($res["data"]["total"])&&$res["data"]["total"]!=0);
        }
        foreach ($history as $k=>$v){
            $history[$k]["shopname"]=$shopinfo["data"][0]["noticeInfo"];
        }
        //开始迭代
        return $history;
    }

    /**
     * 获得闪惠订单
     * @param $condition
     * @return array
     */
    public static function getMeituanSH($condition){
        $meituan=new Meituan();
        $res=$meituan->where("shopid",Session::get("shopid"))->find();
        if(!isset($res["epoiid"])){
            return false;
        }
        if(empty($res["tuantoken"])){
            return false;
        }
        $appAuthToken=$res["tuantoken"];

        $ePoiId=$res['epoiid'];
        $token=$res['token'];
        $time=time();
        $url="http://api.open.cater.meituan.com/waimai/poi/queryPoiInfo?timestamp=$time&appAuthToken=$token&charset=UTF-8&ePoiIds=$ePoiId";
        $signKey=$meituan->SignKey($url);
        $url=$url."&sign=".$signKey;
        $json=curl_get($url);
        $shopinfo=json_decode($json,true);

        $history=[];
        $endtime=date_create($condition["endtime"]);
        $starttime=date_create($condition["starttime"]);
        $diff=date_diff($endtime,$starttime);
        for($i=0;$i<=$diff->days;$i++){
            $date=date("Y-m-d",strtotime("-".$i." day",$endtime->getTimestamp()));
            $page=1;
            do{
                $time = time();
                $url = "http://api.open.cater.meituan.com/shanhui/order/queryListByEpoiId?date=$date&page=$page&pageSize=20&appAuthToken=$appAuthToken&timestamp=$time&charset=utf-8";
                $signKey = $meituan->SignKey($url);
                $url = $url."&sign=".$signKey;
                $json =curl_get($url);
                $res=json_decode($json,true);
                $page++;
                if(isset($res["data"]["orderDTOs"]))$history=array_merge($history,$res["data"]["orderDTOs"]);
            }while(isset($res["data"]["totalPageCount"])&&($page<=$res["data"]["totalPageCount"]));
        }
        foreach ($history as $k=>$v){
            $history[$k]["shopname"]=$shopinfo["data"][0]["noticeInfo"];
        }
        //开始迭代
        return $history;
    }

    /**
     * 获得小菜神数据库中的百度订单数据
     * @param $condition array $post 条件
     * @return array
     */
    private static function getBaidu($condition)
    {
        $bdmodel=new Bdwaimai();
        $bdshopid=$bdmodel->where("shopid",Session::get("shopid"))->find();
        $post_data=[
            "timestamp"=>time(),
            "bdshopid"=>$bdshopid["bdshopid"],
            "shopname"=>$bdshopid["bdshopname"],
            "condition"=>serialize($condition)
        ];
        //CURL 拉取远程数据
        $info=curl_post("http://e.xwdcook.com/index.php/Home/Apiv6/getbdcondtion",$post_data);
        return json_decode($info,true,512,JSON_BIGINT_AS_STRING);
    }


    public static function downorder($getdata){
        $result=self::searchorder($getdata);
        //TODO
        switch ($getdata["platform"]){
            //饿了么
            case "1":
                $elemodel=new Eleorder();
                $res=$elemodel->getorder($getdata);
                self::downele($res);
                break;
            //美团外卖
            case "2":
                $jdmodel=new Jdorder();
                $res=$jdmodel->getOrders($getdata);
                self::downbd($res);
                break;
            //百度外卖
            case "3":
                $res=self::getBaidu($getdata);
                self::downbd($res);
                break;
            //美团点评团购券
            case "4":
                $res=self::getMeituanTG($getdata);
                self::downtg($res);
                break;
            //美团点评闪付
            case "5":
                $res=self::getMeituanSH($getdata);
                self::downsh($res);
                break;
            //百度糯米
            case "6":
                break;
            default:
                break;
        }
        exit();
    }

    /**
     * 下载饿了么格式
     * @param $res
     */
    public static function downele($res){
        $orderlist=[];
        $cellname=[
            array('orderid', '饿了么订单ID'),
            array('address', '顾客送餐地址'),
            array('createdat', '下单时间'),
            array('deliverfee', '配送费'),
            array('delivertime', '预计送达时间'),
            array('description', "订单备注"),
            array('invoice', '发票抬头'),
            array('book', '是否预订单'),
            array('onlinepaid', '是否在线支付'),
            array('phonelist', '顾客联系电话'),
            array('shopname', '店铺名称'),
            array('daysn', '店铺当日订单流水号'),
            array('status', '订单状态'),
            array('refundstatus', '退单状态'),
            array('totalprice','订单总价'),
            array('originalprice','订单原始价格'),
            array('consignee','订单收货人姓名'),
            array('deliverypoiaddress','送餐地址'),
            array('invoiced','订单是否需要发票'),
            array('income','店铺实收'),
            array('servicerate','饿了么服务费率'),
            array('hongbao','餐盒费'),
            array('packagefee','饿了么服务费'),
            array('activitytotal','订单活动金额'),
            array('shoppart','店铺承担活动费用'),
            array('elemepart','饿了么承担活动费用'),
            array("name","菜品名称"),
            array("quantity","菜品数量"),
            array("total","总价"),
        ];

        foreach ($res as $k=>$v){
            $i=0;
            foreach ($v["groups"] as $kk=>$vv){
                foreach ($vv["items"] as $x=>$y){
                    if($i==0){
                        $orderlist[]=[
                            'orderid'=>" ".$v["orderid"],
                            'address'=>$v["address"],
                            'createdat'=>$v["createdat"],
                            'deliverfee'=>$v["deliverfee"],
                            'delivertime'=>$v["delivertime"],
                            'description'=>$v["description"],
                            'invoice'=>$v["invoice"],
                            'book'=>$v["book"],
                            'onlinepaid'=>$v["onlinepaid"],
                            'phonelist'=>$v["phonelist"][0],
                            'shopname'=>$v["shopname"],
                            'daysn'=>$v["daysn"],
                            'status'=>$v["status"],
                            'refundstatus'=>$v["refundstatus"],
                            'totalprice'=>$v["totalprice"],
                            'originalprice'=>$v["originalprice"],
                            'consignee'=>$v["consignee"],
                            'deliverypoiaddress'=>$v["deliverypoiaddress"],
                            'invoiced'=>$v["invoiced"],
                            'income'=>$v["income"],
                            'servicerate'=>$v["servicerate"],
                            'hongbao'=>$v["hongbao"],
                            'packagefee'=>$v["packagefee"],
                            'activitytotal'=>$v["activitytotal"],
                            'shoppart'=>$v["shoppart"],
                            'elemepart'=>$v["elemepart"],
                            "name"=>$y["name"],
                            "quantity"=>$y["quantity"],
                            "total"=>$y["total"]
                        ];
                    }else{
                        $orderlist[]=[
                            "name"=>$y["name"],
                            "quantity"=>$y["quantity"],
                            "total"=>$y["total"]
                        ];
                    }
                    $i++;
                }
            }
        }
        self::toExecl($cellname,$orderlist);

    }

    /**
     * 下载百度,美团格式
     * @param $res
     */
    public static function downbd($res){
        $orderlist=[];
        $status = array(
            20010 => '锁定',
            20020 => '订单取消',
            20040 => '超时未支付系统取消',
            31000 => '等待付款',
            31020 => '已付款',
            41000 => '待处理',
            32000 => '等待出库',
            33040 => '配送中',
            33060 => '已妥投',
            34000 => '京东已收款',
            90000 => '订单完成',
            20030 => '用户申请取消',
            2 => '拣货完成'

        );
        $ordertype = array(
            1 => '饿了么',
            2 => '美团外卖',
            3 => '百度外卖',
            4=>'京东到家'
        );
        $cellname=[
            array('ddh', '订单号'),
            array('sjmc','商家名称'),
            array('dh', '电话'),
            array('dz', '地址'),
            array('ddbz', '订单备注'),
            array('psf', '配送费'),
            array('zffs', '支付方式'),
            array('yhje', '优惠金额'),
            array('sjbt','商家补贴'),
            array('ddly', '订单来源'),
            array('spmc', '商品名称'),
            array('ptsj', "平台售价"),
            array('dgsl', '订购数量'),
            array('dw', "单位"),
            array('jg', '价格'),
            array('ddje',"订单金额"),
            array('khmc',"客户名称"),
            array('ddzt',"订单状态"),
            array('xdsj',"下单时间"),
            array('ddxh',"订单序号"),
            array('chf',"餐盒费"),
            array('yhxx',"优惠信息")
        ];

        foreach ($res as $key=>$val){
            $i=0;
            foreach ($val["details"] as $k=>$v){
                if($i==0){
                    $orderlist[]=[
                        "ddh" => " ".$val['orderid'],
                        "sjmc"=>$val['shopname'],
                        "dh" => $val['buyermobile'],
                        "dz" => $val['buyerfulladdress'],
                        "ddbz" => $val['orderbuyerremark'],
                        "psf" => $val['orderfreightmoney']/100,
                        "zffs" => $val['orderpaytype']==4?"在线支付":"其他方式",
                        "yhje" => $val['orderdiscountmoney']/100,
                        "sjbt"=> $val['salemoney']/100,
                        "ddly" => $ordertype[$val['platform']],
                        "spmc" => $v['skuname'],
                        "ptsj" => $v['skujdprice']/100,
                        "dgsl" => $v['skucount'],
                        "dw" => "",
                        "jg" => $v['skucount']*$v['skujdprice']/100,
                        "ddje"=>$val['orderbuyerpayablemoney']/100,
                        "khmc"=>$val['buyerfullname'],
                        "ddzt"=>$status[$val['orderstatus']],
                        "xdsj"=>$val['orderstarttime'],
                        "ddxh"=>$val['ddxh'],
                        "chf"=>$val['packagingmoney']/100,
                        "yhlx"=>$val['discountname'],
                        "yhxx"=>$val['discountdesc']
                    ];
                }else{
                    $orderlist[]=[
                        "spmc" => $v['skuname'],
                        "ptsj" => $v['skujdprice']/100,
                        "dgsl" => $v['skucount'],
                        "dw" => "",
                        "jg" => $v['skucount']*$v['skujdprice']/100
                    ];
                }
                $i++;
            }
        }
        self::toExecl($cellname,$orderlist);
    }

    /**
     * 下载美团团购格式
     * @param $res
     */
    public static function downtg($res){

        $cellname=[
            array('couponBuyPrice', '团购券购买价格'),
            array('couponCancelStatus', '团购券是否可撤销'),
            array('couponCode', '团购券码'),
            array('couponStatusDesc', '团购券状态'),
            array('couponUseTime', '验券时间'),
            array('dealBeginTime', "团购券对应项目开始售卖时间"),
            array('dealTitle', '项目对应的标题'),
            array('dealValue', '项目售卖价'),
            array('verifyAcct', '验券帐号'),
            array('verifyType', '验券方式')
        ];
        self::toExecl($cellname,$res);
    }

    /**
     * 下载闪惠格式
     * @param $res
     */
    public static function downsh($res){

        $cellname=[
            array('dpOrderCode', '点评订单号'),
            array('serialNumber', '订单800码'),
            array('payTime', '支付时间'),
            array('vendorOrderId', '商家订单号'),
            array('phoneNo', '买单手机号'),
            array('couponOfferTitles', "优惠title"),
            array('canConfirm', '是否可确认'),
            array('canRefund', '是否可退款'),
            array('status', '订单状态'),
            array('activityAmount', '活动金额'),
            array('vendorActivityAmount', '商家承担金额'),
            array('huiActivityAmount', '平台承担金额'),
            array('originalAmount', '原价(单位:元)'),
            array('userPayAmount', '用户实付金额(单位:元)'),
            array('vendorDiscountAmount', '商家优惠金额(单位:元)'),
            array('vendorNoDiscountAmount','不可优惠价格(单位:元)')
        ];
        self::toExecl($cellname,$res);
    }

    /**
     *输出到EXECL
     */
    public static function toExecl($cellname,$orderlist){
        set_time_limit(0);//防止超时
        if(empty($orderlist)){die("数据为空,无法导出!");}
        $xlsTitle = iconv('utf-8', 'gb2312', "导出表".date("Y-m-d H:i:s")); //文件名称
        $fileName = "导出表" . date('_YmdHis'); //or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($cellname);
        $dataNum = count($orderlist);
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        for($i = 0;$i < $cellNum; $i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '1', $cellname[$i][1]);
        }
        // Miscellaneous glyphs, UTF-8
        for($i = 0;$i < $dataNum; $i++){
            for($j = 0; $j < $cellNum; $j++){
                if(isset($orderlist[$i][$cellname[$j][0]]))
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 2), $orderlist[$i][$cellname[$j][0]]);
            }
        }
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls"); //attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
    }

}